// pages/Earnings/Withdraw/Withdraw.js
//获取应用实例
const app = getApp()
const assetsAddress = app.globalData.global.assetsIp + '/' + app.globalData.global.assetsName;
import { getUserAccount , getUser , withdraw , queryUserWechatOpenId } from '../../../api/user';
import { getChannel , queryAppInforMation } from '../../../api/brand';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    assetsAddress: assetsAddress,
    balance: 0,
    amountList: [
      { id: 0, name: '10元', data: 10,},
      { id: 1, name: '30元', data: 30,},
      { id: 2, name: '50元', data: 50,},
      { id: 3, name: '100元', data: 100,},
      { id: 4, name: '500元', data: 200,},
      { id: 5, name: '自定义', data: '',},
    ],
    amount: 10,
    active: '10元',
    showAmountIpt: false,
    serviceCharge: 0, // 提现手续费
    rate: '', // 提现费率
    singleMinAmount: 0, // 最低提现金额
    user: {
      aliAccount: '',
    },
    payPassword: '',
    checked: false,
    openid: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this._getUserAccount();
    this._getChannel();
    this._getUser();
    this._queryUserWechatUnionId();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this._getUserAccount();
    this._getChannel();
    this._getUser();
    setTimeout(() => {
      wx.stopPullDownRefresh({
        success: (res) => {
          console.log(res, '刷新成功')
          wx.showToast({
            title: '刷新成功',
            icon: 'none',
          })
        },
      })
    }, 1000)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    let userId = wx.getStorageSync('userId') ?? 1;
    return {
      path: '/pages/Welcome/Welcome?scene='+userId,
    }
  },
  // 页面跳转
  goNext(e){
    let type = e.target.dataset.type||e.currentTarget.dataset.type;
    let url = e.target.dataset.name||e.currentTarget.dataset.name;
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    // console.log(JSON.stringify(item))
    // return
    if(item){
      if(type == 1){
        wx.switchTab({
          url: `${url}`,
        })
      }else{
        wx.navigateTo({
          url: `${url}?item=${JSON.stringify(item)}`,
        })
      }
    }else{
      if(type == 1){
        wx.switchTab({
          url: `${url}`,
        })
      }else{
        wx.navigateTo({
          url: `${url}`,
          events: {
            updateUser: (data) => {
              console.log(data,'子组件更新订单信息')
              _this._getUser();
            }
          }
        })
      }
    }
  },
  // 获取用户余额信息
  _getUserAccount(){
    let _this = this;
    getUserAccount({})
    .then(res => {
      if(res.success){
        _this.setData({
          balance: res.data.balance,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 获取用户信息
  _getUser(){
    let _this = this;
    getUser({})
    .then(res => {
      if(res.success){
        _this.setData({
          user: res.data,
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 选择提现金额
  selAmount(e){
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    if(item.data == ''){
      this.setData({
        showAmountIpt: true,
      })
    }else{
      this.setData({
        showAmountIpt: false,
      })
    }
    this.setData({
      amount: item.data,
      active: item.name,
    })
  },
  // 获取提现通道
  _getChannel(){
    let _this = this;
    getChannel({channelTag: 'WECHAT_TRANSFER_PAY'})
    .then(res => {
      if(res.success){
        _this.setData({
          serviceCharge: res.data.content.length > 0 ? res.data.content[0].serviceCharge : '',
          rate: res.data.content.length > 0 ? res.data.content[0].rate : '',
          singleMinAmount: res.data.content.length > 0 ? res.data.content[0].singleMinAmount : '',
        })
      }
    })
  },
  // 申请提现
  _withdraw(){
    let _this = this;
    if(!_this.data.checked){
      wx.showToast({
        title: '请阅读并同意隐私协议后再进行操作',
        icon: 'none',
      });
      return;
    }
    if(!_this.data.user.realName || _this.data.user.realName == ''){
      wx.showModal({
        title: '温馨提示',
        content: '当前账号暂未实名认证，是否前往实名？',
        complete: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/Users/RealName/RealName',
              events: {
                updateUser: (data) => {
                  console.log(data,'子组件更新订单信息')
                  _this._getUser();
                }
              }
            })
          }
        }
      });
      return;
    }
    if(_this.data.amount == ''){
      wx.showToast({
        title: '请输入提现金额',
        icon: 'none',
      });
      return;
    }
    if(parseFloat(_this.data.amount) < parseFloat(_this.data.singleMinAmount)){
      wx.showToast({
        title: `最低提现金额不能低于${_this.data.singleMinAmount}元`,
        icon: 'none',
      });
      return;
    }
    if(parseFloat(_this.data.amount) > parseFloat(_this.data.balance)){
      wx.showToast({
        title: `提现金额不能大于当前可提现金额${_this.data.balance}元`,
        icon: 'none',
      });
      return;
    }
    // if(!_this.data.user.aliAccount || _this.data.user.aliAccount == ''){
    //   wx.showModal({
    //     title: '温馨提示',
    //     content: '当前提现支付宝账号暂未绑定，是否前往绑定？',
    //     complete: (res) => {
    //       if (res.confirm) {
    //         wx.navigateTo({
    //           url: '/pages/Users/BindAliAccount/BindAliAccount',
    //           events: {
    //             updateUser: (data) => {
    //               console.log(data,'子组件更新订单信息')
    //               _this._getUser();
    //             }
    //           }
    //         })
    //       }
    //     }
    //   })
    //   return;
    // }
    const child = _this.selectComponent('.pay-passwordAuth');
    console.log(child,'child')
    child.clearPassword();
    child.openPayAuth();
  },
  // 余额支付校验密码成功
  sonSubmitOrder(e){
    console.log(e,'e')
    this.setData({
      payPassword: e.detail,
    })
    this._submitWithdraw();
  },
  // 确认提现
  _submitWithdraw(){
    let _this = this;
    withdraw({withdrawAmount: _this.data.amount,payPassword: _this.data.payPassword,withdrawType: 5,openId: _this.data.openid})
    .then(res => {
      if(res.success){
        wx.showToast({
          title: '提现成功',
          icon: 'none',
        })
        _this._getUserAccount();
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  bindAli(e){
    let _this = this;
    let url = e.target.dataset.name||e.currentTarget.dataset.name;
    if(this.data.user.realName && this.data.user.realName != ''){
      wx.navigateTo({
        url: url,
        events: {
          // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
          updateUser: function(data) {
            _this._getUser();
          }
        }
      })
    }else{
      wx.showModal({
        title: '温馨提示',
        content: '当前账号暂未实名，请先实名后再进行操作',
        complete: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/Users/RealName/RealName',
              events: {
                updateUser: (data) => {
                  console.log(data,'子组件更新订单信息')
                  _this._getUser();
                }
              }
            })
          }
        }
      })
    }
  },
  // 切换是否记住密码
  onChange(event){
    this.setData({
      checked: event.detail,
    });
  },
  // 回收员使用协议
  getAgreement(){
    let _this = this;
    queryAppInforMation({infoType: 2,title: '用户协议'})
    .then(res => {
      if (res.success) {
        if(res.data.content.length > 0){
          var itm = res.data.content[0];
          if(res.data.content[0].jumpUrl && res.data.content[0].jumpUrl.length > 4 && res.data.content[0].jumpUrl.substring(0,4) == 'http'){
            wx.navigateTo({
              url: `/pages/Link/Link/Link?url=${encodeURIComponent(itm.jumpUrl)}&title=${JSON.stringify(itm.title)}`,
            })
          }else if(res.data.content[0].imgUrl){
            wx.navigateTo({
              url: `/pages/Link/LinkImg/LinkImg?url=${encodeURIComponent(itm.imgUrl)}&title=${JSON.stringify(itm.title)}`,
            })
          }else if(res.data.content[0].content){
            wx.navigateTo({
              url: `/pages/Link/LinkText/LinkText?content=${JSON.stringify(itm.content)}&title=${JSON.stringify(itm.title)}`,
            })
          }
        }else{
          wx.showToast({
            title: '暂未获取到使用协议',
            icon: 'none'
          })
        }
      } else {
        wx.showToast({
          title: res.errMessage,
          icon: 'none'
        })
      }
    })
  },
  // 获取用户的Openid
  _queryUserWechatUnionId(){
    let _this = this;
    wx.login({
      success: (logRes) => {
        queryUserWechatOpenId({code: logRes.code})
        .then(res => {
          if(res.success){
            _this.setData({
              openid: res.data.openid
            })
          }else{
            wx.showToast({
              title: res.errMessage,
              icon: 'none',
            })
          }
        })
      }
    })
  },
})